package com.me.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 吕旺平
 * @date 2019/10/24 20:05:50
 * @description
 */
public class ServUtil {
	public static String getRegState(String state, String regex) {
		if (regex == null || regex == "") return null;
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(state);
		if (m.matches()) {
			return state.substring(state.lastIndexOf(".") + 1);
		}
		return null;
	}
	
	public static String parseState(HttpServletRequest req){
		if (req.getParameter("state") != null) return req.getParameter("state");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(20 * 1024 * 1024);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		upload.setSizeMax(-1);
		try {
			List<FileItem> items = upload.parseRequest(req);
			for (FileItem item : items){
				if (item.isFormField()){
					if (item.getFieldName().equals("state")){
						req.setAttribute("items",items);
						return item.getString("utf-8");
					}
				}
			}
		} catch (FileUploadException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
}
